import React, {Component} from "react";
import { Row, Col, Button, Input, Card, Pagination, message, Modal,Form, Upload, Image, Table, Popconfirm, Select } from 'antd'
import { ArrowLeftOutlined, SearchOutlined, PlusCircleOutlined } from '@ant-design/icons'



import './index.less'
import { deletetravel, searchtravel, sendtravel} from '../../api/travel'
import rules from '../../utils/rules'

const { Option } = Select

class Travel extends Component {
  userRef = React.createRef();

  state = {
    travelinfo: {
      category: '遗址',
      picture: '',
    },
    Issearch: false,
    searchList: [],
    keywords: '',
     params: {
      pageNum: 1,
      pageSize: 5,
      content: '',
     },
    total: 0,
    travelList: [],
    isModalVisible: false,
    columns:[
      {
        title: '游记Id',
        dataIndex: 'post_id',
        width: '80px',
        align: 'center' ,
      },
      {
        title: '发布者',
        dataIndex: 'user_name',
        width: '80px',
        align: 'center' ,
      },
      {
        title: '头像',
        dataIndex: 'hesd_portrait',
        width: '80px',
        align: 'center' ,
        render: (_,record) => {
          return <Image width="60px" height="60px" src={record.hesd_portrait} fallback="" ></Image >
        }
      },
      {
        title: '游记图',
        dataIndex: 'picture',
        width: '150px',
        align: 'center' ,
        render: (_,record) => {
          return <Image className="showImage"  src={(record.picture === '') ? '':  record.picture.split(';')[0]} fallback="" ></Image >
        }
      },
      {
        title: '分类',
        dataIndex: 'category',
        width: '120px',
        align: 'center' ,
        editable: true,
      },
      {
        title: '游记内容',
        dataIndex: 'post_content',
        width: '290px',
        align: 'center' ,
        render: (_, record) => {
          return <div className="textHd2">{record.post_content}</div>
        }
      },
      {
        title: '操作',
        align: 'center' ,
        dataIndex: 'operation',
        width: '90px',
        render: (text,record) => {
             return <Popconfirm title="改操作将会有就删除这条数据, 是否继续" onConfirm={() => this.deleteTravel(record.post_id)} okText="确认" cancelText="取消">
              <Button className="deleteBtn">删除</Button>
              </Popconfirm>
        },
      },
    ]
  }

  // 组件创建完成的生命周期
  componentDidMount() {
    this.getTravelList()
  }
  // 获取数据
  getTravelList = async () =>  {
   const res  = await searchtravel(this.state.params)
   const travelList = res.data.data || []
   travelList.map((item, value) => item.key = value)
   const total = res.data.total
   this.setState({travelList,total})
}

// 分页页面跳转
  paginationChange = (e) => {
     const params = {...this.state.params, pageNum: e }
     this.setState({params}, () => {
      this.getTravelList()
     })
}
// 监听enter点击事件
  onKeyup = (e) => {
    if(e.keyCode === 13) {
      this.getSearch()
  }
}

// 开始搜索
getSearch =  () => {
  this.setState({params: {...this.state.params, content:  this.state.keywords}}, async () => {
    const res  = await searchtravel(this.state.params)
    const searchList = res.data.data || []
    const total = res.data.total
    this.setState({searchList, Issearch: true,total})
  })
}

// 返回上一级
back = () => {
  const params = {...this.state.params, content: '', pageNum: 1 }
  this.setState({Issearch: false, params, keywords: ''}, () => {
    this.getTravelList()
  })
}

// 删除用户
deleteTravel = async (id) => {
  const res = await deletetravel(id)
  if (res.code === 200) {
    message.success('删除游记成功')
  } else {
    message.error('删除游记失败')
  }
  this.getTravelList()
}


// 下拉菜单选择
handleSelect = (value) => {
  const category = value
  this.setState({travelinfo: {...this.state.travelinfo, category}})
}

// 气泡确认， 开始表单检验
handleOk =  () => {
  this.userRef.current.submit() 
}

// 表单验证失败
FormError = () => {
  message.error('表单数据有误')
 }

 // 图片上传
 handleChange = (info) => {
  if (info.file.status !== 'uploading') {
  }
  if (info.file.status === 'done') {
    const picture = info.file.response.data.url
    this.setState({travelinfo: {...this.state.travelinfo,picture}})
    message.success('图片上传成功');
  } else if (info.file.status === 'error') {
    message.error('图片上传失败');
  }
 }

 // 添加用户
adduser = async (values) => {
  const travel= {...values, ...this.state.travelinfo}
  const res = await sendtravel(travel)
  if (res.code === 200) {
    message.success('添加数据成功')
    this.setState({isModalVisible: false})
    this.getTravelList()
  } else {
    message.error(res.msg)
  }
}


  render() {
    const { travelList, total, params, isModalVisible, travelinfo, Issearch, keywords, searchList, columns } = this.state
    return (
        <div>
           <Row style={{ height: '46px', display: "flex", alignContent: "center"}}>
      <Col span={3}>{Issearch? <Button type="ghost" icon={<ArrowLeftOutlined />} onClick={() => this.back()} className="backBtn">返回</Button> : null }</Col>
      <Col span={6}><Input placeholder="搜索用户" prefix={<SearchOutlined />} value={keywords} onChange={(e) => {this.setState({keywords: e.target.value})}} onKeyUp={(e) => this.onKeyup(e)}></Input></Col>
      <Col span={2} offset={1}><Button type="primary" icon={<SearchOutlined />} onClick={() => this.getSearch()}>搜索</Button></Col>
      <Col span={2}><Button icon={<PlusCircleOutlined />} onClick={() => { this.setState({isModalVisible: true})}} className="successBtn">增加</Button></Col>
    </Row>
    <Card style={{marginTop: '30px'}}>
      {Issearch ? (<Table 
          pagination={false}
          bordered
          dataSource={searchList}
          columns={columns}></Table>) : 
          (<Table 
          pagination={false}
          bordered
          dataSource={travelList}
          columns={columns}></Table>)}
    </Card>
    <div className="pagination">
   <Pagination showQuickJumper current={params.pageNum} total={total} onChange={this.paginationChange} pageSize={params.pageSize} />
    </div>
    {/* 添加框 */}
    <Modal title="添加用户" okText="确认" cancelText="取消" visible={isModalVisible} onOk={() => this.handleOk()} onCancel={() => {this.setState({isModalVisible: false})}}>
     <Form ref={this.userRef} onFinish={(values) => this.adduser(values)} onFinishFailed={this.FormError}>
         <Form.Item  label="发布者Id" name="userId" rules={rules.userId}>
            <Input  />
            </Form.Item>
         <Form.Item  label="游记内容" name="postContent" rules={rules.postContent}>
            <Input  />
            </Form.Item>
         <Form.Item  label="点赞数" name="likes" rules={rules.likes}>
            <Input   />
            </Form.Item>
         <Form.Item  label="分类" name="category" >
         <Form.Item>
         <Select defaultValue={travelinfo.category} style={{ width: 120 }} onChange={(value) => this.handleSelect(value)}>
          <Option value="遗址">遗址</Option>
          <Option value="乡村">乡村</Option>
          <Option value="都市">都市 </Option>
          <Option value="公园">公园</Option>
          <Option value="其他">其他</Option>
    </Select>
        </Form.Item>
         </Form.Item>
         <Form.Item  label="游记图" name="picture" >
           <Form.Item>
           <Upload  action="http://111.75.252.147:8888/app/scenic/picUpload" name="file" onChange={(info) => this.handleChange(info)}  >
           <Image  src={travelinfo.picture} fallback="" style={{width: '60px', height: '60px'}}></Image >
        </Upload>
           </Form.Item>
            </Form.Item>
       </Form>
      </Modal>
        </div>
    );
  }
}

export default Travel;
